import { def } from '@vue/shared'
import { createRouter, createWebHashHistory } from 'vue-router'

import Layout from '../components/Layout.vue'

const routes = [{
        path: '/login',
        component: () =>
            import ('../view/Login.vue'),
        meta: { title: '登录' },
        hidden: true
    },
    {
        path: '/',
        component: Layout,
        meta: { title: '首页' },
        reairect: '/home',
        hidden: true,
        children: [{
            path: 'home',
            meta: { title: '首页' },
            component: () =>
                import ('../view/Home.vue')
        }]
    },
    {
        path: '/teacher',
        component: Layout,
        meta: { title: '讲师管理', icon: 'Avatar' },
        redirect: '/teacher/list',
        children: [{
                path: 'list',
                meta: { title: '讲师列表' },
                component: () =>
                    import ('../view/teacher/list.vue')
            },
            {
                path: 'create',
                meta: { title: '添加讲师' },
                component: () =>
                    import ('../view/teacher/form.vue')
            }
        ]
    },
    {
        path: '/course',
        component: Layout,
        meta: { title: '课程管理', icon: 'Platform' },
        redirect: '/course/list',
        children: [{
                path: 'list',
                meta: { title: '课程列表' },
                component: () =>
                    import ('../view/course/list.vue')
            },
            {
                path: 'create',
                meta: { title: '添加课程' },
                component: () =>
                    import ('../view/course/form.vue')
            }
        ]
    },


]

//通过createRouter方法创建路由
const router = createRouter({
        history: createWebHashHistory(), //hash模式
        routes
    })
    //全局前置守卫
router.beforeEach((to, from, next) => {
    //若请求的是登陆页面，则放行，否则判断用户是否登录
    //若没有登录，自然跳转到登陆页面
    if (to.path === '/login') {
        next()
    } else {
        //判断用户是否登录(检查localStorage中是否存在token)
        const token = localStorage.getItem('member_token')
        if (token) {
            next()
        } else {
            next('/login')
        }
    }
})

export default router